import { instantiate, Node, NodePool, Prefab } from "cc";

interface IDictPool {
  [name: string]: NodePool;
}

interface IDictPrefab {
  [name: string]: Prefab;
}

class NodePoolManager {
  public static _instance: NodePoolManager = null;

  private constructor() {}

  public static getInstance() {
    if (!this._instance) {
      this._instance = new NodePoolManager();
    }
    return this._instance;
  }

  private _dictPool: IDictPool = {};
  private _dictPrefab: IDictPrefab = {};

  public getNode(prefab: Prefab, parent: Node) {
    let name = prefab.name;
    let node: Node = null;
    this._dictPrefab[name] = prefab;

    const pool = this._dictPool[name];

    if (pool) {
      if (pool.size() > 0) {
        node = pool.get();
      } else {
        node = instantiate(prefab);
      }
    } else {
      this._dictPool[name] = new NodePool();
      node = instantiate(prefab);
    }

    node.setParent(parent);
    node.active = true;
    return node;
  }

  public putNode(node: Node) {
    let name = node.name;
    node.setParent(null);
    if (!this._dictPool[name]) {
      this._dictPool[name] = new NodePool();
    }
    this._dictPool[name].put(node);
  }
}

export const nodePoolManager = NodePoolManager.getInstance();
